/*
 * Copyright (C) 2014 University of Pittsburgh
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * IndexModule.js 
 * 
 * This is a custom module that will be used for the page index.php
 */

//var globalDocumentIdArr = {};
var glDocumentArr = {};
var glCurBeginIndx = 0;
var glCurEndIndx = 0;
var glCurStepSize = 0;

define(
  [
    "dojo/ready",
    "dojo/dom",
    "dojo/on",
    "dijit/registry",
    "dijit/form/Button",
    "dojo/json",
    "dijit/layout/LinkPane",
    "dijit/layout/ContentPane",
    "dojo/request", 
    "dojo/request/notify",
    "dojo/dom-construct",
    "dojo/dom-form",
    "dgrid/List", 
    "dgrid/OnDemandGrid", 
    "dgrid/Selection", 
    "dgrid/Keyboard", 
    "dgrid/editor", 
    "dijit/form/DateTextBox", 
    "dijit/form/HorizontalSlider", 
    "dijit/form/NumberSpinner",
    "dijit/form/Select",
    "dojo/data/ObjectStore",
    "dojo/_base/declare",
    "custom/StaticData",
    "dojo/domReady!"
  ], 

  function(ready, dom, on, registry, Button, JSON, LinkPane, ContentPane, request, notify, domConstruct, domFrm, 
           List, Grid, Selection, Keyboard, editor, DateTextBox, Slider, NumberSpinner, Select, ObjectStore, declare) {

    ready(function() { 
      var html = "";
      // Begin Search Page
      
      // Listen for events from request providers
      notify("send", function(responseData, cancel) {
        var prgrph = domConstruct.create("p");
        prgrph.innerHTML = "Searching ...";
        domConstruct.place(prgrph, "div_search_results", "only");
      });
      
      var buildLinkToDocuments = function() {
        var lnkPaneArr = {};
        for(var i = glCurBeginIndx; i <= glCurEndIndx; ++i) {
          lnkPaneArr[i] = new LinkPane().placeAt("div_search_results", (i == glCurBeginIndx ? "only" :"last"));
          lnkPaneArr[i].set("content", glDocumentArr[i].document_citation);
          lnkPaneArr[i].set("class", "search_results");
          domConstruct.place("<br />", "div_search_results", "last");
          on(lnkPaneArr[i], "click", function(inVal) {
            return function() {
              
              //Select or create the tab container
              var tabContainer = registry.byId("center_panel_tab_container");
              var tabPane = registry.byId("tab_document");
              if(typeof(tabPane) === "undefined" || !tabPane) {
                // Need to create the tab pane
                tabPane = new ContentPane({
                  title: "Document",
                  id: "tab_document",
                  selected: true
                });  
                html = "<h2 style=\"text-align: center;\">Legal and Ethical Indicators of Adaptive Public Health System Response</h2>" +
                      "<br /><div id=\"div_doc_result\"></div>";
                tabPane.set("content", html);
                tabContainer.addChild(tabPane);                        
              }
              
              html = "<h2 style=\"text-align: center\">" + glDocumentArr[inVal].document_citation + "</h2>";
              domConstruct.place(html, "div_doc_result", "only");
              html = "<h3 style=\"text-align: center\">" + glDocumentArr[inVal].document_header + "</h3><hr />";
              domConstruct.place(html, "div_doc_result", "last");
              html = "<h5>" + glDocumentArr[inVal].document_body + "</h5>";
              domConstruct.place(html, "div_doc_result", "last");
              
              //Open the tabpage
              tabContainer.selectChild(tabPane);
            };                                       
          }(i));  
        }  
      };
      
      var buildNavigationPane = function() {
        var navContentPane = new ContentPane().placeAt("div_search_results_nav", "only");        
        navContentPane.set("id", "nav_content_pane");
        navContentPane.set("content", "Records: " + (glCurBeginIndx + 1) + " - " + (glCurEndIndx + 1) + " of " + glDocumentArr.length + "<hr />");
        
        var navButtonPane = new ContentPane().placeAt("div_search_results_nav", "last");
        navButtonPane.set("id", "nav_button_pane");
                        
        // Create 'Back' button if it does not exist
        var btnBack = new Button({
          label: "Back"
        }).placeAt(navButtonPane, "only");
        
        if(glCurBeginIndx == 0) {
          btnBack.set("disabled", true);
        } else {
          btnBack.set("disabled", false);
        }
        on(btnBack, "click", function() {
          glCurBeginIndx -= glCurStepSize;
          glCurEndIndx -= glCurStepSize;
          if(glCurBeginIndx < 0) {
            glCurBeginIndx = 0;
            glCurEndIndx = glCurStepSize - 1;
          }
          buildLinkToDocuments();
          if(glCurBeginIndx == 0) {
            btnBack.set("disabled", true);
          } else {
            btnBack.set("disabled", false);
          }
          if(glCurEndIndx == glDocumentArr.length - 1) {
            btnForward.set("disabled", true);
          } else {
            btnForward.set("disabled", false);
          }
          navContentPane.set("content", "Records: " + (glCurBeginIndx + 1) + " - " + (glCurEndIndx + 1) + " of " + glDocumentArr.length + "<hr />");
        });
        
        // Create 'Next' button
        var btnForward = new Button({
          label: "Next"
        }).placeAt(navButtonPane, "last");
          
        if(glCurEndIndx == glDocumentArr.length - 1) {
          btnForward.set("disabled", true);
        } else {
          btnForward.set("disabled", false);
        }
        on(btnForward, "click", function() {
          glCurBeginIndx += glCurStepSize;
          glCurEndIndx += glCurStepSize;
          if(glCurEndIndx > glDocumentArr.length - 1) {
            glCurBeginIndx = glDocumentArr.length - glCurStepSize;
            glCurEndIndx = glDocumentArr.length - 1;
          }
          buildLinkToDocuments();
          if(glCurBeginIndx == 0) {
            btnBack.set("disabled", true);
          } else {
            btnBack.set("disabled", false);
          }
          if(glCurEndIndx == glDocumentArr.length - 1) {
            btnForward.set("disabled", true);
          } else {
            btnForward.set("disabled", false);
          }
          navContentPane.set("content", "Records: " + (glCurBeginIndx + 1) + " - " + (glCurEndIndx + 1) + " of " + glDocumentArr.length + "<hr />");
        });      
      };  
      
      var frmSrch = registry.byId("frm_search");
      
      // Attach the onsubmit event handler of the form
      on(frmSrch, "submit", function(evt) {

        // prevent the page from navigating after submit
        evt.stopPropagation();
        evt.preventDefault();
        alert("SUBMITTED FORM");
        
        domConstruct.empty("div_search_results");
        
        var searchResultsNavPane = registry.byId("nav_content_pane");
        if(searchResultsNavPane && searchResultsNavPane instanceof ContentPane) {
          //Destroy this widget and it's descendants from the manager object
          searchResultsNavPane.destroyRecursive(false);
        }
        var searchResultsButtonPane = registry.byId("nav_button_pane");
        if(searchResultsButtonPane && searchResultsButtonPane instanceof ContentPane) {
          //Destroy this widget and it's descendants from the manager object
          searchResultsButtonPane.destroyRecursive(false);
        }
        
        //Clear out the node itself
        domConstruct.empty("div_search_results_nav");
        
        
        // Post the data to the server
        request.post("get_documents_matching_search_parameters.php", {
          // Send the form data
          data: domFrm.toObject("frm_search"),
          // Wait 30 seconds for a response
          timeout: 30000,
          // Parse data from JSON to a JavaScript object
          handleAs: "json"
        }).then(function(responseData) {
          var txtBoxNumRec = registry.byId("txt_num_rec");
          var numRec = parseInt(txtBoxNumRec.get("value"));

          if(responseData.phasys_lena_search.error_data.error_code == 1000) {
            glDocumentArr = responseData.phasys_lena_search.document_data;
            if(glDocumentArr == "DATA_NONE") {
              var prgrph = domConstruct.create("p", {"class": "search_error"});
              prgrph.innerHTML = "No records found matching search criteria.";
              domConstruct.place(prgrph, "div_search_results", "only");
            } else {
              glCurStepSize = numRec;
              glCurBeginIndx = 0;
              if(numRec < glDocumentArr.length) {  
                glCurEndIndx = numRec - 1;
                // I need to chop up the list and allow for navigation buttons
                buildLinkToDocuments();  
                buildNavigationPane();
              } else {
                glCurBeginIndx = 0;
                glCurEndIndx = glDocumentArr.length - 1;
                buildLinkToDocuments();    
                buildNavigationPane();
              }
            }
          } else {
            var prgrph = domConstruct.create("p", {"class": "search_error"});
            prgrph.innerHTML = "Error: " + responseData.phasys_lena_search.error_data.error_code + 
                               " " + responseData.phasys_lena_search.error_data.error_message; 
            domConstruct.place(prgrph, "div_search_results", "only");
          }
        }, 
        function(err) {
          // handle an error condition
          var prgrph = domConstruct.create("p", {"class": "search_error"});
          prgrph.innerHTML = "Error: " + err.response.text;
          domConstruct.place(prgrph, "div_search_results", "only");
        });
      });
      
      // End of search page 
      
      
      var stateStore = new ObjectStore({
        objectStore: globalStateStore,
        labelProperty: "name"
      });
      
      var columns = 
        [
          editor({label: 'A Date (editable if after 1999)', 
                  field: 'date', 
                  canEdit: function(object, value){
                                         return value.getFullYear() >= 2000;
                                       } }, DateTextBox),
            editor({label: 'Real Number', 
                    field: 'floatNum'
                   }, Slider),
            editor({label: 'Integer', 
                    field: 'integer',
                    editorArgs: {style: 'width: 5em;', 
                                 constraints: {min:0, 
                                               max:1550, 
                                               places:0}}},
                             NumberSpinner),
            editor({label: 'Text editable if checkbox checked + saved', 
                    field: 'text', 
                    canEdit: function(object) {
                                        return object.bool;
                                      }}, "text", "dblclick"),
                            {label: 'Non-editable text', 
                             field: 'text2', 
                             sortable: false},
            editor({label: 'Another Date', 
                    field: 'date2'}, DateTextBox, "dgrid-cellfocusin"),
            editor({label: 'CheckBox', 
                    field: 'bool'}, "checkbox"),
//            editor({label: 'TestState',
//                    field: 'state2', 
//                    editorArgs: {style: 'width: 6em;'}},
//                    Select),
            editor({label: "Select Store", field: "state", editorArgs: {store: stateStore, maxHeight: 150, style: "width:120px;"}}, Select, "click")
          ];

          window.grid = new (declare([Grid, Selection, Keyboard]))({
                   sort: "id",
                   store: testTypesStore,
                   columns: columns,
                   selectionMode: "single"
                 }, "grid");
                 
                 grid.on("dgrid-datachange", function(evt){
                   console.log("data changed: ", evt.oldValue, " -> ", evt.value);
                   console.log("cell: ", evt.cell, evt.cell.row.id);
                 });
                 grid.on("dgrid-editor-show", function(evt){
                   console.log("show editOn editor: ", evt);
                 });
                 grid.on("dgrid-editor-hide", function(evt){
                   console.log("hide editOn editor: ", evt);
                 });
                 
                 grid.on(".field-integer:dgrid-datachange", function(evt){
                   if(evt.value > 1000){
                     evt.preventDefault();
                     alert("Values above 1000 will be rejected");
                     // log data on a timeout to demonstrate that value wasn't changed
                     setTimeout(function(){
                       console.log("integer after prevented event:",
                         evt.cell.row.data.integer);
                     }, 0);
                   }
         });
    });
  }
);
